<?php

namespace App\Http\Controllers\Admin;

use App\Model\Branch;
use App\Model\BranchTest;
use App\Model\Order;
use App\Model\Order1;
use App\Model\OrderError;
use App\Model\PushOrder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Matrix\Exception;

class PushController extends Controller
{
    //正式
    private $url = "http://openapi.fulu.com/api/getway";

    //品盛
//    private $app_key = "YZ2Fu5Y86kfnF4qIcKCtOK9PjJzlv4w7kq+bPPu0SmeZxjqn5gUBgTAthCnxFOXP";
//    private $app_secret = "10888069844749068c5f6fe742796e0b";

    //普兴
    private $app_key = "k62nIJvlYq9lhEQfrmC1dWhavZFQCsJNX/iC9ivhTnmwjppWUrl28EjHts2tGTZg";
    private $app_secret = "b6888a54dfa143ab9f69f035b831d60d";

    //1成功  2失败  3已推送  4已推送到福禄   5    6直推到福禄

    //测试
//    private $url = "http://pre.openapi.fulu.com/api/getway";
//    private $app_key = "i4esv1l+76l/7NQCL3QudG90Fq+YgVfFGJAWgT+7qO1Bm9o/adG/1iwO2qXsAXNB";
//    private $app_secret = "0a091b3aa4324435aab703142518a8f7";

    //测试福禄直冲接口
    public function testFulu()
    {
        try {
            $order = Order::where(['status' => "未处理"])->first();
            if ($order) {
                switch ($order['remainingnumber']) {
                    case 100:
                        $product_id = 10707887;
                        break;
                    case 200:
                        $product_id = 19016689;
                        break;
                    case 300:
                        $product_id = 19016698;
                        break;
                    case 500:
                        $product_id = 19016699;
                        break;
                    case 1000:
                        $product_id = 19016700;
                        break;
                }
                $resFulu = $this->pushOrderFulu($product_id, $order['orderno'], $order['chargeaccount']);

                if ($resFulu->code == 0) {
                    $infoFulu['branch'] = '已推送快充';
                    $infoFulu['status'] = '已处理';
                    $infoFulu['isok'] = 4;
                    $infoFulu['bid'] = 888;
                    $infoFulu['time'] = time();
                    PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
                } else {
                    $failInfo = '';
                    switch ($resFulu->code) {
                        case    2004:
                            $failInfo = "商户余额不足";
                            break;
                        case    3001:
                            $failInfo = "商品不存在或无法购买";
                            break;
                        case    3002:
                            $failInfo = "商品已下架";
                            break;
                        case    3003:
                            $failInfo = "商品维护中";
                            break;
                        case    3004:
                            $failInfo = "商品在维护期内";
                            break;
                        case    3005:
                            $failInfo = "商品库存不足";
                            break;
                        case    4004:
                            $failInfo = "充值账号在黑名单中";
                            break;
                        case    4010:
                            $failInfo = "外部订单号已存在";
                            break;
                    }
                    $infoFulu['branch'] = $resFulu->code . $failInfo;
                    $infoFulu['status'] = '查询福禄失败原因';
                    $infoFulu['isok'] = 3;
                    $infoFulu['bid'] = 0;
                    PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        //更新下游的平均完成时间
        echo isset($order['id']) ? $order['id'] : 0;
//        print ("<script type=\"text/javascript\">");
//        print ("function fresh_page()");
//        print ("{");
//        print ("window.location.reload();");
//        print ("}");
//        print ("setInterval('fresh_page()',1500);");
//        print ("</script>");
    }

    //直充
    public function testFulu1()
    {
        try {
            $order = Order::where(['isok' => "6"])->first();
            if ($order) {
                switch ($order['price']) {
                    case 100:
                        $product_id = 10707887;
                        break;
                    case 200:
                        $product_id = 19016689;
                        break;
                    case 300:
                        $product_id = 19016698;
                        break;
                    case 500:
                        $product_id = 19016699;
                        break;
                    case 1000:
                        $product_id = 19016700;
                        break;
                }
                $resFulu = $this->pushOrderFulu($product_id, $order['orderno'], $order['chargeaccount'], $order['num']);
                if ($resFulu->code == 0) {
                    $infoFulu['branch'] = '已推送快充';
                    $infoFulu['status'] = '已处理';
                    $infoFulu['isok'] = 4;
                    $infoFulu['bid'] = 888;
                    $infoFulu['time'] = time();
                    Order::where('orderno', $order['orderno'])->update($infoFulu);
                } else {
                    $failInfo = '';
                    switch ($resFulu->code) {
                        case    2004:
                            $failInfo = "商户余额不足";
                            break;
                        case    3001:
                            $failInfo = "商品不存在或无法购买";
                            break;
                        case    3002:
                            $failInfo = "商品已下架";
                            break;
                        case    3003:
                            $failInfo = "商品维护中";
                            break;
                        case    3004:
                            $failInfo = "商品在维护期内";
                            break;
                        case    3005:
                            $failInfo = "商品库存不足";
                            break;
                        case    4004:
                            $failInfo = "充值账号在黑名单中";
                            break;
                        case    4010:
                            $failInfo = "外部订单号已存在";
                            break;
                    }
                    $infoFulu['branch'] = $resFulu->code . $failInfo;
                    $infoFulu['status'] = '查询福禄失败原因';
                    $infoFulu['isok'] = 3;
                    $infoFulu['bid'] = 0;
                    Order::where('orderno', $order['orderno'])->update($infoFulu);
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        //更新下游的平均完成时间
        echo isset($order['id']) ? $order['id'] : 0;
        print ("<script type=\"text/javascript\">");
        print ("function fresh_page()");
        print ("{");
        print ("window.location.reload();");
        print ("}");
        print ("setInterval('fresh_page()',1500);");
        print ("</script>");
    }

    //下单到福禄
    public function pushOrderFulu($product_id, $customer_order_no, $charge_account, $buy_num = 1)
    {
        $param = [
            "product_id" => $product_id,
            "customer_order_no" => $customer_order_no,
            "charge_account" => $charge_account,
            "buy_num" => $buy_num
        ];

        $data = [
            "app_key" => $this->app_key,
            "method" => "fulu.order.direct.add",
            "timestamp" => date("Y-m-d H:i:s", time()),
            "version" => "2.0",
            "format" => "json",
            "charset" => "utf-8",
            "sign_type" => "md5",
            "app_auth_token" => "",
            "biz_content" => json_encode($param),
        ];
        $sign = $this->getSign($data);

        $data['sign'] = $sign;

        $res = $this->curlFulu($this->url, json_encode($data, JSON_UNESCAPED_SLASHES));

        $res = json_decode($res);

        return $res;

    }

    //福禄充值回调
    public function fulu_AutoConfirmOrder(Request $request)
    {
        $result = $request->all();
        if (is_object($result)) {
            $info['ext'] = json_encode($result);
        } else {
            $info['ext'] = $result;
            $result = json_decode($result);
        }
        PushOrder::where("id", 1)->update($info);
        PushOrder::where("orderno", $result->customer_order_no)->update($info);

        if ($result->order_state == "success") {
            $info = ['status' => '已处理', 'branch' => '充值成功', 'isok' => 1, 'oktime' => time()];

            PushOrder::where("orderno", $result->customer_order_no)->update($info);
            //测试时需看order_id是不是拆分的订单号
            $res = PushOrder::where("orderno", $result->customer_order_no)->field("pid")->first();

            $this->checkOrderStatus($res['pid'], $result->order_id, 1);
        } else {
            $info = ['status' => '已处理', 'branch' => '充值失败', 'isok' => 4, 'oktime' => time()];

            PushOrder::where("orderno", $result->customer_order_no)->update($info);
            Order::where("orderno", $result->customer_order_no)->update($info);
            //测试时需看order_id是不是拆分的订单号
            $res = PushOrder::where("orderno", $result->customer_order_no)->field("pid")->first();

            $this->checkOrderStatus($res['pid'], $result->order_id, 2);
        }
    }

    //软游充值回调
    public function ry_AutoConfirmOrder(Request $request)
    {
        try {
            $get = $request->all();
            $info['buyerip'] = json_encode($get);
            PushOrder::where('orderno', $get['orderId'])->update($info);
//            Order1 ::where('orderno',$get['orderId'])->update($info);
            $status = "success";
            switch ($get['code']) {
                case 1:
                    $info = ['branch' => '充值中'];
                    PushOrder::where("orderno", $get['orderId'])->update($info);
//                    Order1::where("orderno",$get['orderId'])->update($info);
                    break;
                case 2:
                    $order = PushOrder::where('orderno', $get['orderId'])->first();
//                    $order = Order1::where('orderno',$get['orderId'])->first();
                    $time = time();
                    $oktime = $time - $order['time'];
                    $info = ['bid' => 12, 'branch' => '充值成功', 'isok' => 1, 'oktime' => $oktime];
                    PushOrder::where("orderno", $get['orderId'])->update($info);
//                    Order1::where("orderno",$get['orderId'])->update($info);
                    if ($order['pid'] == 0) {
                        Order::where("orderno", $get['orderId'])->update($info);
                    }
                    $this->callBackOrderStatus($get['orderId'], 1, time());
                    $this->checkOrderStatus($order['pid'], $get['orderId'], 1);
                    $status = "success";
                    $branch = Branch::where("id", 12)->first();
                    $order1['money'] = $branch['money'] + $order->remainingnumber;
                    $order1['successmoney'] = $branch['successmoney'] + $order->remainingnumber;
                    $order1['successnum'] = $branch['successnum'] + 1;
                    Branch::where("id", 12)->update($order1);
                    break;
                case 3:
                    $order = Order::where('orderno', $get['orderId'])->first();
                    switch ($order['price']) {
                        case 100:
                            $product_id = 10707887;
                            break;
                        case 200:
                            $product_id = 19016689;
                            break;
                        case 300:
                            $product_id = 19016698;
                            break;
                        case 500:
                            $product_id = 19016699;
                            break;
                        case 1000:
                            $product_id = 19016700;
                            break;
                    }
                    $resFulu = $this->pushOrderFulu($product_id, $order['orderno'], $order['chargeaccount'], $order['num']);
                    if ($resFulu->code == 0) {
                        $infoFulu['branch'] = '已推送快充';
                        $infoFulu['status'] = '已处理';
                        $infoFulu['isok'] = 4;
                        $infoFulu['bid'] = 888;
                        Order::where('orderno', $order['orderno'])->update($infoFulu);
                        PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
                    } else {
                        $infoFulu['branch'] = $resFulu->code;
                        $infoFulu['status'] = '查询福禄失败原因';
                        $infoFulu['isok'] = 4;
                        $infoFulu['bid'] = 0;
                        Order::where('orderno', $order['orderno'])->update($infoFulu);
                        PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
                    }
                    break;
                default:
                    $info = ['branch' => '超时'];
            }
            return $status;
        } catch (Exception $e) {
            echo "error";
        }
    }

    //软游订单推送
    public function ryPushOrder()
    {
        try {
            //控制是否推单给下线
            $branch = Branch::where("id", 12)->first();
            if ($branch['tel'] == 1) {
                $order = DB::select("select id,buytime,chargeaccount,remainingnumber,price,num,orderno from tiktok_pushorder where status = '未处理'   order by id asc limit 1");
//                $order = DB::select("select id,buytime,chargeaccount,remainingnumber,num,orderno from tiktok_order1 where status = '未处理'   order by id asc limit 1");
                $num = Branch::where("tel", 1)->count();
                if (isset($order[0])) {

                    $order1 = $order[0];
                    $order = (array)$order1;
                    if ($order['id'] % $num == 0) {
                        $res = $this->ry_PushOrder($order['chargeaccount'], $order['orderno'], $order['remainingnumber']);
                        $info['ext'] = $res;
                        PushOrder::where("orderno", $order['orderno'])->update($info);
//                        Order1::where("orderno",$order['orderno'])->update($info);
                        $res = json_decode($res);
                        if ($res->status == 200) {
                            $info['status'] = '已处理';
                            $info['branch'] = '已推送,等待反馈';
                            $info['isok'] = 3;
                            $info['bid'] = 12;
                            $info['time'] = time();
                            PushOrder::where('orderno', $order['orderno'])->update($info);
                            Order::where('orderno', $order['orderno'])->update($info);
//                            Order1::where('orderno', $order['orderno'])->update($info);
                            $branch = Branch::where("id", 12)->first();
                            $orderInfo['num'] = $branch['num'] + 1;
                            $orderInfo['money'] = $branch['money'] + $order['remainingnumber'];
                            Branch::where("id", $branch['id'])->update($orderInfo);
                        }
                    }
                }


            }

            //更新下游的平均完成时间
            echo isset($order['id']) ? $order['id'] : 0;
            print ("<script type=\"text/javascript\">");
            print ("function fresh_page()");
            print ("{");
            print ("window.location.reload();");
            print ("}");
            print ("setInterval('fresh_page()',2000);");
            print ("</script>");

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    //软游测试充值回调
//    public function ry_AutoConfirmOrder(Request $request){
//        try{
//            $get = $request -> all();
//            $info['buyerip'] = json_encode($get);
////            PushOrder ::where('orderno',$get['orderId'])->update($info);
//            Order1 ::where('orderno',$get['orderId'])->update($info);
//            $status = "success";
//            switch ($get['code']){
//                case 1:
//                    $info = ['branch'=>'充值中'];
////                    PushOrder::where("orderno",$get['orderId'])->update($info);
//                    Order1::where("orderno",$get['orderId'])->update($info);
//                    break;
//                case 2:
////                    $order = PushOrder::where('orderno',$get['orderId'])->first();
//                    $order = Order1::where('orderno',$get['orderId'])->first();
//                    $time = time();
//                    $oktime = $time - $order['time'];
//                    $info = ['bid'=>12,'branch'=>'充值成功','isok'=>1,'oktime'=>$oktime];
//                    Order1::where("orderno",$get['orderId'])->update($info);
////                    PushOrder::where("orderno",$get['orderId'])->update($info);
////                    if($order['pid'] == 0){
////                        Order::where("orderno",$get['orderId'])->update($info);
////                    }
////                    $this->callBackOrderStatus($get['orderId'],1,time());
////                    $this->checkOrderStatus($order['pid'],$get['orderId'],1);
////                    $status = "success";
////                    $branch = Branch::where("id",12)->first();
////                    $order1['money'] = $branch['money'] + $order->remainingnumber;
////                    $order1['successmoney'] = $branch['successmoney'] + $order->remainingnumber;
////                    $order1['successnum'] = $branch['successnum'] + 1;
////                    Branch::where("id",12)->update($order1);
//                    break;
//                case 3:
//                    $info = ['bid'=>12,'branch'=>'充值失败','isok'=>2];
//                    Order1::where("orderno",$get['orderId'])->update($info);
//                    break;
//                default:
//                    $info = ['branch'=>'超时'];
//                    Order1::where("orderno",$get['orderId'])->update($info);
//            }
//            return $status;
//        }catch (\Exception $e){
//            echo "error";
//        }
//    }
//
//    //软游测试订单推送
//    public function ryPushOrder(){
//        try{
//            //控制是否推单给下线
//            $branch = Branch::where("id",12)->first();
//            if($branch['tel'] == 1){
////                $order = DB::select("select id,buytime,chargeaccount,remainingnumber,num,orderno from tiktok_pushorder where status = '未处理'   order by id asc limit 1");
//                $order = DB::select("select id,buytime,chargeaccount,remainingnumber,num,orderno from tiktok_order1 where status = '未处理'   order by id asc limit 1");
//                $num = Branch::where("tel",1)->count();
//                if(isset($order[0])){
//
//                    $order1 = $order[0];
//                    $order = (array)$order1;
//                    if($order['id'] % $num == 0) {
//                        $res = $this->ry_PushOrder($order['chargeaccount'], $order['orderno'], $order['remainingnumber']);
//                        $info['ext'] = $res;
////                        PushOrder::where("orderno",$order['orderno'])->update($info);
//                        Order1::where("orderno",$order['orderno'])->update($info);
//                        $res = json_decode($res);
//                        if($res -> status == 200){
//                            $info['status'] = '已处理';
//                            $info['branch'] = '已推送,等待反馈';
//                            $info['isok'] = 3;
//                            $info['bid'] = 12;
//                            $info['time'] = time();
//                            PushOrder::where('orderno', $order['orderno'])->update($info);
////                            Order::where('orderno', $order['orderno'])->update($info);
//                            Order1::where('orderno', $order['orderno'])->update($info);
//                            $branch = Branch::where("id",12)->first();
//                            $orderInfo['num'] = $branch['num'] + 1;
//                            $orderInfo['money'] = $branch['money'] + $order['remainingnumber'];
//                            Branch::where("id",$branch['id'])->update($orderInfo);
//                        }else{
//                            $this -> testFulu();
//                        }
//                    }
//                }
//
//
//            }
//
//            //更新下游的平均完成时间
//            echo isset($order['id']) ? $order['id']:0;
////            print ("<script type=\"text/javascript\">");
////            print ("function fresh_page()");
////            print ("{");
////            print ("window.location.reload();");
////            print ("}");
////            print ("setInterval('fresh_page()',2000);");
////            print ("</script>");
//
//        }catch (Exception $e){
//            echo $e->getMessage();
//        }
//    }

    //软游   推送方法
    public function ry_PushOrder($dyid, $orderid, $money, $num = 1)
    {
        $count = [50, 100, 200, 300, 500, 1000];
        if (in_array($money, $count)) {
            switch ($money) {
                case 50:
                    $goodsCode = 'goods_201';
                    break;
                case 100:
                    $goodsCode = 'goods_202';
                    break;
                case 200:
                    $goodsCode = 'goods_203';
                    break;
                case 300:
                    $goodsCode = 'goods_204';
                    break;
                case 500:
                    $goodsCode = 'goods_205';
                    break;

            }
            $time = time() . rand(100, 999);
            $callBackUrl = 'http://112.124.24.221/admin/push/ry_AutoConfirmOrder';
            $sign = md5('zmypcennn9businessCode=business_21businessOrderId=' . $orderid . 'callBackUrl=' . $callBackUrl . 'chargeCode=' . $dyid . 'goodsCode=' . $goodsCode . 'num=' . $num . 'timeStamp=' . $time . 'tradeIp=127.0.0.1zmypcennn9');

            $post = [
                'businessCode' => 'business_21',
                'businessOrderId' => $orderid,
                'callBackUrl' => $callBackUrl,
                'chargeCode' => $dyid,
                'goodsCode' => $goodsCode,
                'num' => 1,
                'sign' => $sign,
                'timeStamp' => $time,
                'tradeIp' => '127.0.0.1'
            ];
            $json_post = json_encode($post);
            return $this->ry_curl_post_https('http://api.rytjsj.com:60000/business-center/order/sendOrder', $json_post, $orderid);
        }

    }

    //检查订单状态是否全部完成
    public function checkOrderStatus($pid, $orderno, $status)
    {
        if ($pid == 0) {
            if ($status == 1) {
                $info = ['status' => '已处理', 'branch' => '充值成功', 'isok' => 1];
            } else {
                $info = ['status' => '已处理', 'branch' => '充值失败', 'isok' => 2];
            }
            $this->callBackOrderStatus($orderno, $status, time());
            Order::where('orderno', $orderno)->update($info);

        } else {
            $order = Order::where("id", $pid)->first();
            $price = $order['remainingnumber'];
            $money = intval(PushOrder::where(['pid' => $pid, 'isok' => 1])->sum('remainingnumber'));
            $failmoney = intval(PushOrder::where(['pid' => $pid, 'isok' => 2])->sum('remainingnumber'));
            if ($money == $price) {
                $info = ['bid' => 888, 'status' => '已处理', 'branch' => '充值成功', 'isok' => 1];
                Order::where('orderno', $order['orderno'])->update($info);
                OrderError::where('orderno', $order['orderno'])->delete();
                $this->callBackOrderStatus($order['orderno'], 1, time());
            } elseif ($failmoney == $price) {
                $info = ['bid' => 888, 'status' => '已处理', 'branch' => '充值失败', 'isok' => 2];
                Order::where('orderno', $order['orderno'])->update($info);
                OrderError::where('orderno', $order['orderno'])->delete();
                $this->callBackOrderStatus($order['orderno'], 2, time());
            } elseif ($price == $money + $failmoney) {
                if ($price <= 100) {
                    $info = ['bid' => 888, 'status' => '已处理', 'branch' => '充值失败', 'isok' => 2];
                    Order::where('orderno', $order['orderno'])->update($info);
                    $this->callBackOrderStatus($order['orderno'], 2, time());
                } else {
                    $info = ['bid' => 888, 'status' => '已处理', 'branch' => '充值成功', 'isok' => 1];
                    Order::where('orderno', $order['orderno'])->update($info);
                    $this->callBackOrderStatus($order['orderno'], 1, time());
                }
            } else {
                $info = ['status' => '已处理', 'branch' => '正在拆分充值', 'isok' => 5];
                Order::where('orderno', $order['orderno'])->update($info);
//                $info = ['orderno'=>$order['orderno'],'bid'=>$order['id'],'time'=>time()];
                $order['time'] = time();
                $res = OrderError::where("orderno", $order['orderno'])->first();
                if ($res == null) {
                    OrderError::where('orderno', $order['orderno'])->create($order);
                }
            }
        }
    }

    //手动查询
    public function getOrderInfo(Request $request)
    {
        $product_id = $request->get('id');
        $table = $request->get('table');
        $param = [
            "customer_order_no" => $product_id
        ];
        $data = [
            "app_key" => $this->app_key,
            "method" => "fulu.order.info.get",
            "timestamp" => date("Y-m-d H:i:s", time()),
            "version" => "2.0",
            "format" => "json",
            "charset" => "utf-8",
            "sign_type" => "md5",
            "app_auth_token" => "",
            "biz_content" => json_encode($param),
        ];
        $sign = $this->getSign($data);

        $data['sign'] = $sign;

        $res = $this->curlFulu($this->url, json_encode($data, JSON_UNESCAPED_SLASHES));

        $res = json_decode($res);

        $result = json_decode($res->result);
        $oktime = time() - strtotime($result->create_time);

        if ($table == 'PushOrder') {
            $orderInfo = PushOrder::where('orderno', $result->customer_order_no)->first();

            if ($result->order_state == "success") {

                $info = ['branch' => '充值成功', 'isok' => 1, 'oktime' => $oktime];
                PushOrder::where("orderno", $result->customer_order_no)->update($info);
                $this->checkOrderStatus($orderInfo['pid'], $result->customer_order_no, 1);

            } elseif ($result->order_state == "processing") {
                $info = ['branch' => '充值中', 'isok' => 4];
            } elseif ($result->order_state == "failed") {
                $info = ['status' => '已处理', 'branch' => '充值失败', 'isok' => 2, 'oktime' => $oktime, 'ext' => json_encode($result)];
                PushOrder::where("orderno", $result->customer_order_no)->update($info);

                if ($orderInfo['pid'] == 0) {
                    Order::where("orderno", $result->customer_order_no)->update($info);
                    $this->callBackOrderStatus($result->customer_order_no, 2, time());
                } else {
                    $this->checkOrderStatus($orderInfo['pid'], $result->customer_order_no, 2);
                }
            } else {
                $info = ['branch' => '未处理', 'isok' => 4, 'oktime' => $oktime, 'ext' => json_encode($result)];
            }
            PushOrder::where("orderno", $result->customer_order_no)->update($info);
        } else {
            if ($result->order_state == "success") {
                $this->callBackOrderStatus($result->customer_order_no, 1, time());
                $info = ['branch' => '充值成功', 'isok' => 1, 'oktime' => $oktime];
                Order::where("orderno", $result->customer_order_no)->update($info);
            } elseif ($result->order_state == "processing") {
                $info = ['branch' => '充值中', 'isok' => 4];
            } elseif ($result->order_state == "failed") {
                $this->callBackOrderStatus($result->customer_order_no, 2, time());
                $info = ['status' => '已处理', 'branch' => '充值失败', 'isok' => 2, 'oktime' => $oktime, 'ext' => json_encode($result)];
                Order::where("orderno", $result->customer_order_no)->update($info);
            } else {
                $info = ['branch' => '未处理', 'isok' => 4, 'oktime' => $oktime, 'ext' => json_encode($result)];
            }
            PushOrder::where("orderno", $result->customer_order_no)->update($info);
        }
    }

    //定时查询福禄充值状态
    public function orderInfo()
    {
        $orders = PushOrder::where(["isok" => 4])->get();
        foreach ($orders as $order) {
            $url = "http://112.124.24.221/admin/push/getOrderInfo?id=" . $order['orderno'] . "&table=PushOrder";
            $this->curlGet($url, 'get');
        }

        $orders = Order::where(["isok" => 4])->get();
        foreach ($orders as $order) {
            $url = "http://112.124.24.221/admin/push/getOrderInfo?id=" . $order['orderno'] . "&table=Order";
            $this->curlGet($url, 'get');
        }
        //更新下游的平均完成时间
        echo isset($order['id']) ? $order['id'] : 0;
        print ("<script type=\"text/javascript\">");
        print ("function fresh_page()");
        print ("{");
        print ("window.location.reload();");
        print ("}");
        print ("setInterval('fresh_page()',3000);");
        print ("</script>");
    }

    //五色石订单推送
    public function fivePushOrder()
    {
        try {
            //控制是否推单给下线
            $branch = Branch::where("id", 15)->first();
//            $branch = BranchTest::where("id",15)->first();
            if ($branch['tel'] == 1) {
                $order = DB::select("select id,buytime,chargeaccount,remainingnumber,price,num,orderno from tiktok_pushorder where status = '未处理'   order by id asc limit 1");
//                $order = DB::select("select id,buytime,chargeaccount,remainingnumber,price,num,orderno from tiktok_order1 where status = '未处理'   order by id asc limit 1");
                $num = Branch::where("tel", 1)->count();
                if (isset($order[0])) {
                    $order1 = $order[0];
                    $order = (array)$order1;
                    if ($order['id'] % $num == 0) {
                        $res = $this->fivePush($order['orderno'], $order['chargeaccount'], $order['remainingnumber']);
                        $info['ext'] = $res;
                        PushOrder::where("orderno", $order['orderno'])->update($info);
//                        Order1::where("orderno",$order['orderno'])->update($info);
                        $res = json_decode($res);
                        if ($res->code == 200) {
                            $info['status'] = '已处理';
                            $info['branch'] = '已推送,等待反馈';
                            $info['isok'] = 3;
                            $info['bid'] = 15;
                            $info['time'] = time();
                            PushOrder::where('orderno', $order['orderno'])->update($info);
                            Order::where('orderno', $order['orderno'])->update($info);
//                            Order1::where('orderno', $order['orderno'])->update($info);
                            $branch = Branch::where("id", 15)->first();
                            $orderInfo['num'] = $branch['num'] + 1;
                            $orderInfo['money'] = $branch['money'] + $order['remainingnumber'] * $order['num'];
                            Branch::where("id", $branch['id'])->update($orderInfo);
                        }
                    }
                }


            }

            //更新下游的平均完成时间
            echo isset($order['id']) ? $order['id'] : 0;
//            print ("<script type=\"text/javascript\">");
//            print ("function fresh_page()");
//            print ("{");
//            print ("window.location.reload();");
//            print ("}");
//            print ("setInterval('fresh_page()',2000);");
//            print ("</script>");

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    //五色石推送方法
    public function fivePush($customer_order_no, $charge_account, $money)
    {
        $url = "120.77.13.96:8124/supply/order/orderCheck";
        $callBackUrl = 'http://112.124.24.221/admin/push/fiveAutoConfirmOrder';
        $key = "060012ff024e8f8a672ea2ab8ad645e7";
        $data1 = [
            "merchantId" => 216,
            "orderType" => 1,
            "mobile" => $charge_account,
            "tradeNoThird" => $customer_order_no,
            "amount" => number_format($money, 2),
            "notifyUrl" => $callBackUrl,
            "businessType" => 3
        ];
        $data = "merchantId=216&orderType=1&mobile=" . $charge_account . "&tradeNoThird=" . $customer_order_no . "&amount=" . number_format($money, 2) . "&notifyUrl=" . $callBackUrl . "&businessType=3";

        $str = implode("", $data1) . $key;

        $sign = md5($str);

        $data = $data . "&signstr=" . $sign;

        $res = $this->curlPost($url, $data);

        return $res;
    }

    //五色石充值回调
    public function fiveAutoConfirmOrder(Request $request)
    {
        try {
            $get = $request->all();
            $info['buyerip'] = json_encode($get);
            PushOrder::where('orderno', $get['tradeNoThird'])->update($info);
//            Order1 ::where('orderno',$get['tradeNoThird'])->update($info);
            $status = "success";
            switch ($get['code']) {
                case 200:
                    $order = PushOrder::where('orderno', $get['tradeNoThird'])->first();
//                    $order = Order1::where('orderno',$get['tradeNoThird'])->first();
                    $time = time();
                    $oktime = $time - $order['time'];
                    $info = ['bid' => 15, 'branch' => '充值成功', 'isok' => 1, 'oktime' => $oktime];
                    PushOrder::where("orderno", $get['tradeNoThird'])->update($info);
//                    Order1::where("orderno",$get['tradeNoThird'])->update($info);
                    if ($order['pid'] == 0) {
                        Order::where("orderno", $get['tradeNoThird'])->update($info);
                    }
                    $this->callBackOrderStatus($get['tradeNoThird'], 1, time());
                    $this->checkOrderStatus($order['pid'], $get['tradeNoThird'], 1);
                    $status = "success";
                    $branch = Branch::where("id", 15)->first();
                    $order1['money'] = $branch['money'] + $order->remainingnumber;
                    $order1['successmoney'] = $branch['successmoney'] + $order->remainingnumber;
                    $order1['successnum'] = $branch['successnum'] + 1;
                    Branch::where("id", 15)->update($order1);
                    break;
                case 300:
                    /**********测试start*********/
//                    $order = Order1::where('orderno',$get['tradeNoThird'])->first();
//                    $time = time();
//                    $oktime = $time - $order['time'];
//                    $info = ['bid' => 15, 'branch' => '充值失败', 'isok' => 2, 'oktime' => $oktime];
//                    Order1::where("orderno",$get['tradeNoThird'])->update($info);
//                    return "success";
//                    die;
                    /**********测试end*********/
                    $order = PushOrder::where('orderno', $get['tradeNoThird'])->first();
                    switch ($order['remainingnumber']) {
                        case 100:
                            $product_id = 10707887;
                            break;
                        case 200:
                            $product_id = 19016689;
                            break;
                        case 300:
                            $product_id = 19016698;
                            break;
                        case 500:
                            $product_id = 19016699;
                            break;
                        case 1000:
                            $product_id = 19016700;
                            break;
                    }
                    $resFulu = $this->pushOrderFulu($product_id, $order['orderno'], $order['chargeaccount']);
                    if ($resFulu->code == 0) {
                        $infoFulu['branch'] = '已推送快充';
                        $infoFulu['status'] = '已处理';
                        $infoFulu['isok'] = 4;
                        $infoFulu['bid'] = 888;
                        Order::where('orderno', $order['orderno'])->update($infoFulu);
                        PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
                    } else {
                        $infoFulu['branch'] = $resFulu->code;
                        $infoFulu['status'] = '查询福禄失败原因';
                        $infoFulu['isok'] = 4;
                        $infoFulu['bid'] = 0;
                        Order::where('orderno', $order['orderno'])->update($infoFulu);
                        PushOrder::where('orderno', $order['orderno'])->update($infoFulu);
                    }
                    break;
                default:
                    $info = ['branch' => '超时'];
            }
            return $status;
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    //华通   订单推送
    public function htPushOrder()
    {
        try {
            //控制是否推单给下线
            $branch = Branch::where("id", 10)->first();
            if ($branch['tel'] == 1) {
                $order = Order::where("status", '未处理')->where('chargetype', 1)->first();
                if (isset($order)) {
                    $order['remainingnumber'] = $order['remainingnumber'] * $order['num'];
                    $res = $this->pushOrder($order['chargeaccount'], $order['orderno'], $order['remainingnumber']);
                    $info['ext'] = $res;
                    Order::where("orderno", $order['orderno'])->update($info);
                    $res = json_decode($res);

                    if ($res->code == "success") {
                        $info['status'] = '已处理';
                        $info['branch'] = '已推送,等待反馈';
                        $info['isok'] = 3;
                        $info['bid'] = 10;
                        $info['customerorderno'] = $res->data->trans_sn;

                        Order::where('orderno', $order['orderno'])->update($info);
                        $branch = Branch::where("id", 10)->first();
                        $orderInfo['num'] = $branch['num'] + 1;
                        $orderInfo['money'] = $branch['money'] + $order['remainingnumber'];
                        Branch::where("id", $branch['id'])->update($orderInfo);
                    } else {
                        $info['branch'] = $res->msg;
                        $info['status'] = '已处理';
                        $info['isok'] = 3;
                        $info['bid'] = 0;
                        Order::where('orderno', $order['orderno'])->update($info);
                    };
                }
            }

            //更新下游的平均完成时间
//            echo $order['id'];
            print ("<script type=\"text/javascript\">");
            print ("function fresh_page()");
            print ("{");
            print ("window.location.reload();");
            print ("}");
            print ("setInterval('fresh_page()',3000);");
            print ("</script>");

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    //华通  推送方法
    public function pushOrder($dyid, $orderid, $money)
    {
        $post = [
            'ChargeAccount' => $dyid,
            'ChargeValue' => $money,
            'ChargeType' => 10,//具体类型可查看文档
            'SupBuyNum' => 1,//固定值1
            'OrderType' => 1,//订单类型：填写1
            'Id' => $orderid
        ];
        $arr['data'] = $this->aes_encrypt(json_encode($post), '60b2a07bca1666f5', 1111111111111111);
        $arr['mchid'] = 205;
        $arr['notifyurl'] = 'http://112.124.24.221/admin/push/autoConfirmOrder';
        return $this->curl_post_https('http://me.sd.7080.cn:8080/?c=pay&m=create', $arr, $orderid);//这里返回json数据   {"code":"success","msg":"创建订单成功","data":{"trans_sn":平台系统订单号}}
    }


    //自动推送确认订单isok
    //0订单列表显示已启用，默认
    //1订单完成
    //2订单列表显示已停用，失败反馈给福禄
    public function autoConfirmOrder(Request $request)
    {
        try {
            $post = file_get_contents('php://input');
            $post = json_decode($post, true);
            $post = $post['PostData'];
//            $post = str_replace(' ','+',$post);//将获取到的aes数据中的空格替换成+号

            $post = $this->aes_decrypt($post, '60b2a07bca1666f5', '1111111111111111');//进行aes解密


            $post1 = strstr($post, '}', true) . "}";//截取}之前的字符串  去掉}以及之后的乱码  再在字符串结尾补齐}
            $post = json_decode($post1, true);//json数据转数组
            $status = "error";
            switch ($post['Status']) {
                case 2:
                    $order = Order::where('orderno', $post['OrderNo'])->first();
                    $time = time();
                    $oktime = $time - strtotime($order['buytime']);
                    $info = ['branch' => '充值失败', 'isok' => 2, 'time' => $time, 'oktime' => $oktime, 'ext' => $post1];
                    callBackOrderStatus($post['OrderNo'], 2, $time);
                    $status = "success";
                    break;
                case 3:
                    $order = Order::where('orderno', $post['OrderNo'])->first();
                    $time = time();
                    $oktime = $time - $order['buytime'];
                    $info = ['branch' => '充值成功', 'isok' => 1, 'time' => $time, 'oktime' => $oktime, 'ext' => $post1];
                    callBackOrderStatus($post['OrderNo'], 1, $time);
                    $status = "success";
                    $branch = Branch::where("id", 10)->first();
                    $orderInfo['successnum'] = $branch['successnum'] + 1;
                    $orderInfo['successmoney'] = $branch['successmoney'] + $order['remainingnumber'];
                    Branch::where("id", $branch['id'])->update($orderInfo);
                    break;
                default:
                    $info = ['branch' => '超时'];
            }
            Order::where("orderno", $post['OrderNo'])->update($info);
            return $status;
        } catch (Exception $e) {
            $e->getMessage();
        }
    }

    //AES-128-ECB加密   data 字符串
    function aes_encrypt($data, $key, $iv = '')
    {
        $str_padded = $data;
        if (strlen($str_padded) % 16) {
            $str_padded = str_pad($str_padded, strlen($str_padded) + 16 - strlen($str_padded) % 16, "\0");
        }
        $data = openssl_encrypt($str_padded, 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv);
        return base64_encode($data);
    }

    //AES-128-ECB解密  data 字符串
    function aes_decrypt($data, $key, $iv = '')
    {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv);
    }

    function curl_post_https($url, $data, $orderid)
    { // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['OrderNo' => $orderid, 'UserID' => 81]); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    function ry_curl_post_https($url, $data, $orderid)
    { // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    public function curlPost($url, $post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'charset=utf-8'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function curlFulu($url, $post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function callBackOrderStatus($orderId, $orderStatus, $time, $str = 'Serge#57$768rtv0')
    {

        $sign = strtoupper(md5($orderId . $orderStatus . $time . $str));

        if ($orderStatus == 1) {
            $postData = "OrderId=" . $orderId . "&OrderStatus=" . $orderStatus . "&Description=充值成功&RealCost=0&Currency=RMB&SubstituteAccount=外部商户042&ChannelAccountId=外部商户042&Ts=" . $time . "&Sign=" . $sign;
        } else {
            $postData = "OrderId=" . $orderId . "&OrderStatus=" . $orderStatus . "&Description=充值失败&RealCost=0&Currency=RMB&SubstituteAccount=外部商户042&ChannelAccountId=外部商户042&Ts=" . $time . "&Sign=" . $sign;
        }


        $url = "http://interface.qsios.cn:8136/actionapi/Order/CallBackOrderStatus";

        $res = $this->curlPost($url, $postData);

        return $res;
    }

    public function getSign($Parameters)
    {
        //签名步骤一：把字典json序列化
        $json = json_encode($Parameters, JSON_UNESCAPED_SLASHES);
        //签名步骤二：转化为数组
        $jsonArr = $this->mb_str_split($json);
        //签名步骤三：排序
        sort($jsonArr);
        //签名步骤四：转化为字符串
        $string = implode('', $jsonArr);
        //签名步骤五：在string后加入secret
        $string = $string . $this->app_secret;
        //签名步骤六：MD5加密
        $result_ = strtolower(md5($string));
        return $result_;
    }

    function mb_str_split($str)
    {
        return preg_split('/(?<!^)(?!$)/u', $str);
    }

    public function curlGet($url, $method, $post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        } elseif ($method == 'get') {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
//        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1");
//        curl_setopt($ch, CURLOPT_PROXYPORT, "2802");
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
